package com.inibb.app.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

@SuppressWarnings( "unchecked" )
public class SimpleHibernateTemplate<T, PK extends Serializable> extends HibernateDaoSupport {

	protected Logger logger = LoggerFactory.getLogger( getClass() );

	public void saveOrUpdate (final T entity) {
		this.getHibernateTemplate().saveOrUpdate(entity);
		logger.debug( "save or update entity: {}", entity );
	}

	public void delete (final T entity) {
		this.getHibernateTemplate().delete(entity);
		logger.debug( "delete entity: {}", entity );
	}

	/**
	 * List By HQL
	 * 
	 * @param hql
	 *            hql语句
	 * @param values
	 *            数量可变的参数
	 */
	public List find (String hql, Object... values) {
		return createQuery(hql, values).list( );
	}


	/**
	 * Query unique object by hql
	 */
	public Object findUnique (String hql, Object... values) {
		return createQuery( hql, values ).uniqueResult( );
	}

	/**
	 * 按HQL查询Intger类形结果.
	 */
	public Integer findInt (String hql, Object... values) {
		return (Integer) findUnique( hql, values );
	}

	/**
	 * 按HQL查询Long类型结果.
	 */
	public Long findLong (String hql, Object... values) {
		return (Long) findUnique( hql, values );
	}

	/**
	 * 根据查询函数与参数列表创建Query对象,后续可进行更多处理,辅助函数.
	 */
	public Query createQuery (String queryString, Object... values) {
		Query queryObject = getSession().createQuery( queryString );
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				queryObject.setParameter( i, values[i] );
			}
		}
		return queryObject;
	}
	

	
}